import { TableColumns } from '@/pages/Template/components/TableColumns';
import { Input, Tabs } from 'antd';
import TabPane from 'antd/es/tabs/TabPane';
import React, { useRef, useState } from 'react';

type TargetKey = React.MouseEvent | React.KeyboardEvent | string;

type TabItem = {
  label: string;
  children: React.ReactNode;
  key: string;
  closable?: boolean;
  editing?: boolean;
}[];
const originalConsoleError = console.error;
const ColumnsTabs: React.FC = () => {
  const [items, setItems] = useState<TabItem>([]);
  const [activeKey, setActiveKey] = useState(items?.[0]?.key);
  const newTabIndex = useRef(0);
  const onChange = (newActiveKey: string) => {
    setActiveKey(newActiveKey);
  };

  const add = () => {
    const newActiveKey = `${newTabIndex.current++}`;
    const newLabel = 'New Tab';
    const newPanes = [...items];
    newPanes.push({
      label: newLabel,
      children: <TableColumns label={newLabel} />,
      key: newActiveKey,
    });
    setItems(newPanes);
    setActiveKey(newActiveKey);
  };

  const remove = (targetKey: TargetKey) => {
    let newActiveKey = activeKey;
    let lastIndex = -1;
    items.forEach((item, i) => {
      if (item.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const newPanes = items.filter((item) => item.key !== targetKey);
    if (newPanes.length && newActiveKey === targetKey) {
      if (lastIndex >= 0) {
        newActiveKey = newPanes[lastIndex].key;
      } else {
        newActiveKey = newPanes[0].key;
      }
    }
    setItems(newPanes);
    setActiveKey(newActiveKey);
  };

  const onEdit = (
    targetKey: React.MouseEvent | React.KeyboardEvent | string,
    action: 'add' | 'remove',
  ) => {
    if (action === 'add') {
      add();
    } else {
      remove(targetKey);
    }
  };

  const onTabDoubleClick = (key: string) => {
    const updatedItems = items.map((item) =>
      item.key === key ? { ...item, editing: true } : item,
    );
    setItems(updatedItems);
  };

  const onTabBlur = (key: string, event: React.FocusEvent<HTMLInputElement>) => {
    const updatedItems = items.map((item) =>
      item.key === key
        ? {
            ...item,
            editing: false,
            label: event.target.value,
            inputValue: event.target.value,
            children: <TableColumns label={event.target.value} />,
          }
        : item,
    );
    setItems(updatedItems);
  };
  // 忽略Tabs.TabPane浏览器控制台过时警告
  console.error = (...args) => {
    if (
      args[0] &&
      args[0].includes &&
      args[0].includes('[antd: Tabs] `Tabs.TabPane` is deprecated.')
    ) {
      return;
    }
    // 对于其他警告，保持原有的控制台输出
    originalConsoleError(...args);
  };
  return (
    <Tabs type="editable-card" onChange={onChange} activeKey={activeKey} onEdit={onEdit}>
      {items.map((item) => (
        <TabPane
          key={item.key}
          tab={
            item.editing ? (
              <Input defaultValue={item.label} autoFocus onBlur={(e) => onTabBlur(item.key, e)} />
            ) : (
              <span onDoubleClick={() => onTabDoubleClick(item.key)}>{item.label}</span>
            )
          }
        >
          {item.children}
        </TabPane>
      ))}
    </Tabs>
  );
};

export default ColumnsTabs;
